package com.lzx.library.dowload;

import androidx.lifecycle.LifecycleOwner;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.PathUtils;
import com.lzx.library.utils.AddressToName;
import com.rxjava.rxlife.RxLife;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import rxhttp.wrapper.param.RxHttp;

/**
 * <pre>
 *     author : 张辉
 *     e-mail : 397243131@qq.com
 *     time   : 2021/07/28
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class DownloadManager {

    private volatile static DownloadManager instance;

    private Channel mChannel = Channel.LZX;

    public static DownloadManager getInstance() {
        if (instance == null) {
            synchronized (DownloadManager.class) {
                if (instance == null) {
                    instance = new DownloadManager();
                }
            }
        }
        return instance;
    }

    public void setChannel(Channel channel) {
        this.mChannel = channel;
    }

    public void updateVersion(LifecycleOwner owner, DownloadListener listener) {
        RxHttp.get("/v1/apkManagement/queryVersionInfo")
                .addHeader("eqCode", DeviceUtils.getUniqueDeviceId())
                .addHeader("packageName", AppUtils.getAppPackageName())
                .setDomainToBaseDownloadUrlIfAbsent()
                .addHeader("companyType", mChannel.code + "")
                .asClass(DownloadBean.class).as(RxLife.<DownloadBean>asOnMain(owner)).subscribe(new Consumer<DownloadBean>() {
            @Override
            public void accept(DownloadBean bean) throws Exception {
                if (bean.getCode() == 1000) {
                    if (bean.getResult() == null) {
                        listener.onFaile("返回数据为空");
                    } else if (Integer.valueOf(bean.getResult().getVersioncode()) <= AppUtils.getAppVersionCode()) {
                        listener.onFaile("当前已是最新版本");
                    } else {
                        listener.onSuccess(bean.getResult().getUrl(), bean.getResult().getVersiondesc());
                    }
                } else {
                    listener.onFaile(bean.getMsg());
                }
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                listener.onFaile(throwable.getMessage());
            }
        });
    }

    /**
     * 断点下载，带进度
     *
     * @param url
     * @param listener
     */
    public void download(String url, DownloadListener listener) {
        String destPath = PathUtils.getInternalAppFilesPath() + "/" + AddressToName.getDownLoadName(url);

        RxHttp.get(url)
                .asAppendDownload(destPath, AndroidSchedulers.mainThread(), progress -> { //
                    //下载进度回调,0-100，仅在进度有更新时才会回调
                    int currentProgress = progress.getProgress(); //当前进度 0-100
                    long currentSize = progress.getCurrentSize(); //当前已下载的字节大小
                    long totalSize = progress.getTotalSize();     //要下载的总字节大小
                    listener.onProgress(currentProgress, currentSize, totalSize);

                }) //指定回调(进度/成功/失败)线程,不指定,默认在请求所在线程回调
                .subscribe(s -> { //s为String类型
                    //下载成功，处理相关逻辑
                    listener.onDownloadSuccess(s);

                }, throwable -> {
                    //下载失败，处理相关逻辑
                    listener.onFaile(throwable.getMessage());
                });
    }
}
